﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using EnvDTE;
using System.Xml;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.ComponentModel;
using System.ComponentModel.Design;


namespace ProjectBase.Guidance.Helpers
{
    internal static class Utils
    {
        internal static bool SafeToBool(string val, bool defaultValue)
        {
            if (string.IsNullOrEmpty(val))
            {
                return defaultValue;
            }
            else
            {
                bool res;
                if (bool.TryParse(val, out res))
                {
                    return res;
                }
                else
                {
                    return defaultValue;
                }
            }
        }

        internal static string Evaluate(string expression, IDictionaryService ds)
        {
            ExpressionEvaluationService evaluator = new ExpressionEvaluationService();
            ServiceAdapterDictionary sa = new ServiceAdapterDictionary(ds);
            if (string.IsNullOrEmpty(expression))
            {
                return SafeToString(expression);
            }
            else
            {
                return SafeToString(evaluator.Evaluate(expression, sa));
            }
        }

        internal static string SafeToString(object val)
        {
            return val == null ? String.Empty : String.Format(CultureInfo.InvariantCulture, "{0}", val);
        }

        internal static string AttributeByName(XmlAttribute[] attributes, string name)
        {
            string res = string.Empty;
            if (attributes != null)
            {
                foreach (XmlAttribute attribute in attributes)
                {
                    if (attribute.Name == name)
                    {
                        res = attribute.Value;
                        break;
                    }
                }
            }
            return res;
        }
    }
}
